package com.qf.mpswaggershiro.shopcart.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qf.mpswaggershiro.shopcart.entity.ShoppingCart;
import com.qf.mpswaggershiro.shopcart.service.IShoppingCartService;
import com.qf.mpswaggershiro.vo.Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 购物车  前端控制器
 * </p>
 *
 * @author cui
 * @since 2023-02-16
 */
@CrossOrigin
@RestController
@RequestMapping("/shopcart")
public class ShoppingCartController {
    @Autowired
    IShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public Vo add(@RequestBody ShoppingCart shoppingCart){

        //添加购物车日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = dateFormat.format(new Date());

        shoppingCart.setCartTime(dateStr);

        shoppingCartService.save(shoppingCart);

        return Vo.ok();
    }

    /**
     * 购物车列表接口
     * @param userId
     * @return
     */
    @GetMapping("/list")
    public Vo list(Integer userId){

        List<ShoppingCart> data = shoppingCartService.listShoppingCart(userId);

        return Vo.ok(data);
    }

    /**
     * 更新购物车商品数量
     * @param num
     * @param cid
     * @return
     */
    @PutMapping("/update/{cid}/{num}")
    public Vo update(@PathVariable String num,@PathVariable Integer cid){
    UpdateWrapper<ShoppingCart> shoppingCartUpdateWrapper = new UpdateWrapper<>();
    shoppingCartUpdateWrapper.set("cart_num",num)
            .eq("cart_id",cid);

        boolean update = shoppingCartService.update(shoppingCartUpdateWrapper);
        if (update){
            return Vo.ok();
        }else {
            return Vo.error();
        }



    }

    /**
     * 结算页面查询接口
     * @param cids
     * @return
     */
    @GetMapping("/listbycids")
    public Vo listbycids(String cids){
       List<ShoppingCart> data= shoppingCartService.listCids(cids);

       return Vo.ok(data);
    }

}
